package com.midongtech.news;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import java.net.URLDecoder;

public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";
    private WebView mWebView;
    private ProgressBar progressbar;
    private TitleBar titlebar;
    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();
        initView();
    }


    private void initView() {
        titlebar = findViewById(R.id.titlebar);
        titlebar.setTitleText("资讯赚");
        titlebar.setCloseListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finishPage();
            }
        });
        mWebView = findViewById(R.id.webview);
        progressbar = findViewById(R.id.progressbar);
        initWebSettingForWebkit(mWebView, progressbar);
        mWebView.addJavascriptInterface(this, "midong");

        String newsTitle = getIntent().getStringExtra("newsTitle");
        titlebar.setTitleText(newsTitle);
        String url = getIntent().getStringExtra("newsUrl");

        Log.e(TAG, "url: " + url);
        mWebView.loadUrl(url);


        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(TAG, "shouldOverrideUrlLoading:" + url);

                return shouldOverrideUrlLoadingImpl(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return shouldOverrideUrlLoading(view, request.getUrl().toString());
            }


            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);

            }

            @Override
            public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
                super.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);

            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                super.onReceivedSslError(webView, sslErrorHandler, sslError);

            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);

            }
        });


        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                uploadFile = uploadMsg;
                openFileChooserBelow5();
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.e(TAG, "onProgressChanged: " + newProgress);
            }
        });

    }

    public boolean shouldOverrideUrlLoadingImpl(WebView view, String url) {
        if (!url.startsWith("http")) {
            AppUtils.openDeepLink(view.getContext(), url);
            return true;//是直达广告，拦截
        }
        return false;
    }


    @android.webkit.JavascriptInterface
    public void openNewPage(String url, String title) {
        Log.i(TAG, "openNewActivity:" + url + "  title:" + title);
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("newsUrl", url);
        intent.putExtra("newsTitle", title);
        startActivity(intent);
    }


    @android.webkit.JavascriptInterface
    public void showAppToast(String msg) {
        Log.i(TAG, "showToast:" + msg);
        showToast(msg);
    }

    @android.webkit.JavascriptInterface
    public void finishPage() {
        Log.i(TAG, "finishPage");
        finish();
    }


    @android.webkit.JavascriptInterface
    public boolean isAppInstalled(String packageName) {
        boolean isAppInstalled = AppUtils.isAppInstalled(mContext, packageName);
        Log.i(TAG, packageName + "  isAppInstalled:" + isAppInstalled);
        return isAppInstalled;
    }


    @android.webkit.JavascriptInterface
    public void openDeeplink(String url) {
        Log.i(TAG, "openDeeplink:" + url);
        AppUtils.openDeepLink(mContext, url);
    }

    @Override
    public void onBackPressed() {
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        callH5Action(mWebView, "refreshPage()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearHistory();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_REQUEST_CODE:
                    Uri imageUri;
                    try {
                        String path = BitmapUtil.getImagePathFromURI(MainActivity.this, data.getData());
                        Bitmap bitmap = BitmapUtil.getCompressBimage(path);
                        //转成url
                        imageUri = Uri.parse(MediaStore.Images.Media.insertImage(
                                getContentResolver(), bitmap, null, null));
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e("hyw", "onActivityResult CHOOSE_REQUEST_CODE Exception:" + e.getMessage());
                        imageUri = data == null || resultCode != Activity.RESULT_OK ? null
                                : data.getData();
                    }
                    if (null != uploadFile) {
                        uploadFile.onReceiveValue(imageUri);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        uploadFiles.onReceiveValue(new Uri[]{imageUri});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (null != uploadFiles) {
                uploadFiles.onReceiveValue(null);
                uploadFiles = null;
            }
        }
    }

}

